<?php
// +----------------------------------------------------------------------
// | 食得鲜 [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.shidexian.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 何锐 <poptser@foxmail.com>  [ ON THE WAY ]
// +----------------------------------------------------------------------
// | DateTime：2016-8-3 16:05:07
// +----------------------------------------------------------------------

namespace YMApi\Controller;
use Think\Controller;
//use Com\TPWechat;

//信息发送API

class SmsapiController extends Controller
{

    /**
     * 测试发送短信
     * @return bool
     */
    public function test_push(){

        $url = "http://localhost:82/index.php?s=/Smsapi/send_message_url";
        $data['message_code'] =  'order_refund';
        $data['user_phone'] =  15820245055;
        $data['user_name'] =  "何锐";
        $data['order_sn'] =  "这里是订单号";
        $data['user_rank'] =  0;
        $data['ver_code'] = 0 ;
        $data['user_id'] =  1;
        $post['data'] = json_encode($data);
        $re = http_post($url,$post);

        if($re){
            dump("ok");
        }else{
            dump("fail");
        }

    }
    public function index(){

    }
    /**
     *发送短信请求API URL
     */
    public function send_message_url(){

        $get_data = $_POST['data'];
        $Json_Data = json_decode($get_data, true);    //JSON 编码

        $R = $this->send_message_api($Json_Data['message_code'],$Json_Data['user_phone'],$Json_Data['user_name'],$Json_Data['user_rank'],$Json_Data['order_sn'],$Json_Data['ver_code'],$Json_Data['user_id'],$Json_Data['remark']);

        if($R){
            w_log("log","返回成功状态");
            exit(json_encode(array('state' => 1)));
        }else{
            w_log("log","返回失败状态");
            exit(json_encode(array('state' => 0)));
        }
    }

    /**
     * 发送短信API 
     * @param $message_code
     * @param $user_phone
     * @param null $user_name
     * @param int $user_rank
     * @param null $order_sn
     * @param null $ver_code
     * @return bool
     * @throws Exception
     */
    public function send_message_api($message_code, $user_phone, $user_name =0, $user_rank =0, $order_sn=0, $ver_code=0,$user_id=0,$remark = array(),$meting_time=null){

        ///
        if(!empty($order_sn)){
            $data = M("order_info")->where("add_time < 1472400001 and order_sn =".$order_sn)->find();
            //判断此订单 是否创建时间早于 2016/8/29 0:00:01
            if($data){
                return true;
                exit();
            }
        }

		if($user_phone=='18903012888'){
			return true;
            exit;
		}

        $phone = array($user_phone);
        //send_message_api_netease
        switch ($message_code){
            case "comment_201702":
                //评价201702
                $template_id = 3051026;
                $param =array($user_name,$order_sn,urldecode($remark['url']));
                $action = "尊敬的".$user_name."，您的订单".$order_sn."显示已签收。宝贝到手还满意吗？简短点评，都是食得鲜万千鲜友期待的参考意见，产品体验师上墙传送门%s".$remark['url'];
                break;
            case "Recharge_gift":
                //充值赠送
                $template_id = 3039119;
                $param =array($user_name,$remark['amount'],$remark['gift']);
                $action = "
尊敬的".$user_name."，您的账户已成功充值".$remark['amount']."，赠送".$remark['gift']."，请在微信公众号联系客服，赠品将为您送货上门，感谢您使用食得鲜";
                break;
            case "Recharge_1000":
                //圣诞充值1000
                $template_id = 3037070;
                $param =array($user_name,$remark['amount']);
                $action = "
尊敬的".$user_name."，您的账户已成功充值".$remark['amount']."，赠送有机鸭稻米5斤+299元埃沃领带定制一条，请在微信公众号联系客服，赠品将为您送货上门，感谢您使用食得鲜";
                break;
            case "Recharge_2980":
                //圣诞充值2980
                $template_id = 3037071;
                $param =array($user_name,$remark['amount']);
                $action = "尊敬的".$user_name."，您的账户已成功充值".$remark['amount']."，赠送神灯机器人或魔镜机器人，以及赠送有机鸭稻米10斤+1件价值599元埃沃衬衫定制券，请在微信公众号联系客服，赠品将为您送货上门，感谢您使用食得鲜";
                break;
            case "Recharge_9800":
                //圣诞充值9800
                $template_id = 3031726;
                $param =array($user_name,$remark['amount']);
                $action = "尊敬的".$user_name."，您的账户已成功充值".$remark['amount']."，赠送小宝机器人，以及有机鸭稻米20斤+3件价值599元埃沃衬衫定制券，请在微信公众号联系客服，赠品将为您送货上门，感谢您使用食得鲜";
                break;
            case "order_warning_new":
                //自提1天未领取提醒
                $template_id = 3030506;
                $param =array($user_name,substr($order_sn,-8),$meting_time);
                $action = "尊敬的".$user_name."，您昨天有一份自提订单".substr($order_sn,-8)."未领取，请于".$meting_time."前往门店领取，逾期系统将自动为您取消订单。门店地址：天河区黄埔大道西120号高志大厦B1层食得鲜智能生活体验中心";
                break;
            case "order_remind_new":
                //自提未领取提醒
                $template_id = 3030504;
                $param =array($user_name,substr($order_sn,-8),$meting_time);
                $action = "尊敬的".$user_name."，您今天有一份自提订单".substr($order_sn,-8)."未领取，请于".$meting_time."前往门店领取，逾期系统将自动为您取消订单。门店地址：天河区黄埔大道西120号高志大厦B1层食得鲜智能生活体验中心";
                break;
            case "order_booking_self_new":
                //预售单自提（新）
                $template_id = 3032504;
                $param =array($user_name,substr($order_sn,-8),$remark['time']);
                $action = "尊敬的".$user_name."，您的订单尾号".substr($order_sn,-8)."包含预售商品，请于".$remark['time']."前往门店领取，逾期系统将自动为您取消订单。门店地址：天河区黄埔大道西120号高志大厦B1层食得鲜智能生活体验中心";
                break;
            case "order_pay_ok_self_new":
                //支付成功-自提(新)
                $template_id = 3029522;
                $param =array($user_name,substr($order_sn,-8),$remark['time']);
                $action = "尊敬的".$user_name."，您的订单尾号".substr($order_sn,-8)."已支付成功，请于".$remark['time']."前往门店领取，逾期系统将自动为您取消订单。门店地址：天河区黄埔大道西120号高志大厦B1层食得鲜智能生活体验中心";
                break;
            case "order_confirm_sendmsg":
                //收货成功后的2小时后发送
                $template_id = 3030232;
                $param =array($user_name,$order_sn,urldecode($remark['url']));
                $action = "尊敬的".$user_name."，您的订单".$order_sn."已显示签收，如您对商品满意请告诉我们，如不满意请告诉大家，食得鲜让您的生活领鲜一步，健康领先一大步！点击链接".$remark['url'];
                break;
            case "activity_60_100_arrived":
                //充60送100支付通知
                $template_id = 3033328;
                $param =array($user_name,$remark['amount']);
                $action = "尊敬的".$user_name."，您的账户已成功充值".$remark['amount']."，请到“我的余额”中查看，感谢您使⽤⾷得鲜";
                break;
            case "activity_60_100":
                //充60送100支付通知
                $template_id = 3034322;
                $param =array($user_name,$remark['amount']);
                $action = "尊敬的".$user_name."，您的账户充值已成功，该活动充值的".$remark['amount']."将在11月16号到账，请关注账户余额变动，感谢您使食得鲜";
                break;
            case "goods_arrive_favorite":
                //到货通知
                $template_id = 3034127;
                $param =array($user_name,$remark['goods_name']);
                $action = "尊敬的".$user_name.",您登记的".$remark['goods_name']."已到货，已自动将该商品加入收藏，欢迎前往食得鲜购买。";
                //尊敬的%s,您所订购的商品已成功支付，订单号:%s,请耐心等待配送
                break;
            case "order_pay_ok":
                //订单支付成功
                $template_id = 3031023;
                if(gmtime()>local_mktime(0,0,0,1,27,2017) && gmtime()<local_mktime(0,0,0,2,3,2017)){
                    $order_sn.='，春节假期，可能稍有晚点，配送员已在快马加鞭';
                }
                $param =array($user_name,$order_sn);
                $action = "尊敬的".$user_name.",您所订购的商品已成功支付，订单号:".$order_sn.",请耐心等待配送";
                //尊敬的%s,您所订购的商品已成功支付，订单号:%s,请耐心等待配送
                break;
            case "order_distribution":
                $template_id = 3031024;
                $param =array($user_name,$order_sn);
                $action = "尊敬的".$user_name."，您的订单:".$order_sn."已经在配送中，请保持手机畅通。";
                //订单开始配送
                break;
            case "order_finish":
                $template_id = 3034026;
                $param =array($user_name,$order_sn);
                $action = "尊敬的".$user_name.",您所订购的商品订单号".$order_sn."已经成功送达，食得鲜祝您生活愉快";
                //订单完成
                //尊敬的%s,您所订购的商品订单号:%s已经成功送达，食得鲜祝您生活愉快
                break;
            case "order_finish_self":
               	$template_id = 3029155;
               	$param =array($user_name,$order_sn);
               	$action = "尊敬的".$user_name.",您所订购的商品订单号".$order_sn."已经自提取货，食得鲜祝您生活愉快";
               	//订单完成
               //尊敬的%s,您所订购的商品订单号%s已经自提取货，食得鲜祝您生活愉快
               	break;
            case "order_refund":
                $template_id = 3031025;
                $param =array($user_name,$order_sn);
                $action = "尊敬的".$user_name.",您的退货退款已经成功(订单号:".$order_sn.")，请注意查收退款消息";
                //订单退款
                break;
            case "ver_code":
                $template_id = 3032025;
                $param =array($ver_code);
                $action = "短信验证码,验证码:".$ver_code;
                //短信验证码
                break;
            case "shipping_start_notice" :
            	$template_id = 3030099;
            	if(gmtime()>local_mktime(0,0,0,1,27,2017) && gmtime()<local_mktime(0,0,0,2,3,2017)){
            	    $remark['best_time'].='，春节假期，可能稍有晚点，配送员已在快马加鞭';
            	}
            	$param = array($user_name,$order_sn,$remark['phone'],$remark['best_time']);
            	$action = "尊敬的".$user_name."，您的订单".$order_sn."已经在配送中，配送员".$remark['phone']."，预计到达时间为".$remark['best_time']."，请保持手机畅通。";
            	//尊敬的%s，您的订单%s已经在配送中，配送员%s，预计到达时间为%s，请保持手机畅通。
            	break;
            case "distribute_start" :
            	$template_id = 3031156;
            	if(gmtime()>local_mktime(0,0,0,1,27,2017) && gmtime()<local_mktime(0,0,0,2,3,2017)){
            	    $remark['best_time'].='，春节假期，可能稍有晚点，配送员已在快马加鞭';
            	}
            	$param = array($user_name,$order_sn,$remark['best_time']);
            	$action = "尊敬的".$user_name."，您的订单".$order_sn."已经在配送中，预计到达时间".$remark['best_time']."，请保持手机畅通。";
            	//尊敬的%s，您的订单%s已经在配送中，预计到达时间%s，请保持手机畅通。
            	break;
            case "shipping_pickup_notice":
            	$template_id = 3029083;
            	$param =array($user_name,$remark['take_no'],$remark['meet_time'],$remark['meet_address'],$remark['phone']);
            	$action = "尊敬的".$user_name."，您的取件号为".$remark['take_no']."，请".$remark['meet_time']."分钟内到".$remark['meet_address']."取件。配送员".$remark['phone'];
            	//尊敬的%s，您的取件号为%s，请%s分钟内到%s取件。配送员%s
            	break;
            case "shipping_arrive_notice":
            	$template_id = 3032058;
            	$param =array($order_sn,$remark['meet_time'],$remark['meet_address'],$remark['shipper_moblie']);
            	$action = "您好，您的取件号为".$order_sn."，请".$remark['meet_time']."分钟内到".$remark['meet_address']."取件。配送员".$remark['shipper_moblie'];
            	break;
            case "order_remind":
                $template_id = 3030082;
                $param =array($user_name,$order_sn,$meting_time);
                $action = "尊敬的".$user_name."，您今天有一份自提订单".$order_sn."未领取，请于".$meting_time."之前前往领取";
                //尊敬的%s，您今天有一份自提订单%s未领取，请于%s之前前往领取。
                break;
            case "order_warning":
                $template_id = 3032056;
                $param =array($user_name,$order_sn,$meting_time);
                $action = "尊敬的".$user_name."，您今天有一份自提订单".$order_sn."，请于".$meting_time."之前前往领取，过时将自动取消订单";
                //尊敬的%s，您昨天有一份自提订单%s未领取，请于%s之前前往领取，过时将自动取消订单。
                break;
            case "order_cancel":
                $template_id = 3032057;
                $param =array($user_name,$order_sn);
                $action = "尊敬的".$user_name."，由于您过时仍未领取自提订单".$order_sn."，该订单已经取消。";
                //尊敬的%s，由于您过时仍未领取自提订单%s，该订单已经取消。
                break;
            case "order_pay_ok_distribute":
            	$template_id = 3033117;
            	if(gmtime()>local_mktime(0,0,0,1,27,2017) && gmtime()<local_mktime(0,0,0,2,3,2017)){
            	    $remark['best_time'].='，春节假期，可能稍有晚点，配送员已在快马加鞭';
            	}
                $param =array($user_name,$order_sn,$remark['best_time']);
                $action = "尊敬的".$user_name."，您所订购的商品已支付成功，订单号".$order_sn."，预计配送时间".$remark['best_time']."，请耐心等待配送。";
                //尊敬的%s，您所订购的商品已支付成功，订单号%s，预计配送时间%s，请耐心等待配送。
            	break;
            case "order_pay_ok_self":
                $template_id = 3029176;
                $param =array($user_name,$order_sn);
                $action = "尊敬的".$user_name."，您所订购的商品订单号".$order_sn."已支付成功，门店地址请查看订单详情，请尽快前往取货。";
                //尊敬的%s，您所订购的商品订单号%s已支付成功，门店地址请查看订单详情，请尽快前往取货。
            	break;
            case "goods_arrive":
                $template_id = 3034127;
                $param =array($user_name);
                $action = "尊敬的".$user_name."，您登记的".$remark['goods_name']."已到货，欢迎前往⾷食得鲜购买";
                //尊敬的%s，您登记的%s已到货，欢迎前往⾷食得鲜购买。
                break;
            case "describe_order_notice":
              	$template_id = 3031270;
               	$param =array($user_name,$order_sn);
               	$action = "尊敬的".$user_name."，您的订单".$order_sn."配送员无法与您取得联系已延迟发货，请于到微信公众号与客服联系修改配送时间，或拨打客服电话400-830-2108";
               	//尊敬的%s，您的订单%s配送员无法与您取得联系已延迟发货，请于到微信公众号与客服联系修改配送时间，或拨打客服电话400-830-2108
               	break;
            case "delayed_delivery_notice":
            	$template_id = 3029241;
            	if(gmtime()>local_mktime(0,0,0,1,27,2017) && gmtime()<local_mktime(0,0,0,2,3,2017)){
            	    $remark['best_time'].='，春节假期，可能稍有晚点，配送员已在快马加鞭';
            	}
               	$param =array($user_name,$order_sn,$remark['best_time']);
               	$action = "尊敬的".$user_name."，您的订单".$order_sn."延迟配送的时间为".$remark['best_time']."，请耐心等待配送";
               	//尊敬的%s，您的订单%s延迟配送的时间为%s，请耐心等待配送。
               	break;
			case "order_cancel_pickup":
				$template_id = 3032057;
				$param = array($user_name, $order_sn);
				$action = "尊敬的{$user_name}，您的订单{$order_sn}已取消，退款将在1-3个工作日内退回您的账户，请注意查收，欢迎再次光临食得鲜";
				break;
			case 'order_pickup_warning_new':
				$template_id = 3036033;
				$param = array($user_name,substr($order_sn,-8),$meting_time);
				$action = "尊敬的{$user_name}，您昨天有一份自提订单{$order_sn}未领取，请于{$meting_time}前往门店领取，今天内未领取系统将自动为您取消订单。门店地址：天河区黄埔大道西120号高志大厦B1层食得鲜智能生活体验中心。";
				break;

			case 'buy_now_notice':
				$template_id = 3034583;
				$param = array($user_name,$remark['goods_name']);
				$action = "尊敬的{$user_name}，您订阅的{$remark['goods_name']}在5分钟后开始秒杀，赶紧上食得鲜提前加入购物车吧!";
				break;
            case 'order_refund_new':
                $template_id = 3039239;
                $param = array($user_name,substr($order_sn,-8),$remark['refund_amount']);
                $action = "尊敬的{$user_name}，您的订单号{$order_sn}部分商品缺货为您退款，退款商品信息请查看订单详情，抱歉给您带来的不便，退款金额{$remark['refund_amount']}将在1-3个工作日内返回到您的原支付账户，请注意查收。";
                break;
//            case 'order_refund_new':
//                $template_id = 3031025;
//                $param = array($user_name,substr($order_sn,-8),$remark['refund_amount']);
//                $action = "尊敬的{$user_name}，您的订单号{$order_sn}部分商品缺货为您退款，退款商品信息请查看订单详情，抱歉给您带来的不便，退款金额{$remark['refund_amount']}将在1-3个工作日内返回到您的原支付账户，请注意查收。";
//                break;
            default:
                return false;//参数错误
                break;
        }

        //$send_data = true;
        $send_data = $this->send_message_api_netease($template_id,$phone,$param);

//        模版id
        $my_id = M("mail_templates")->where(array("template_code"=>$message_code))->getField("template_id");

        if($send_data){
            $this->write_message_log($user_phone,1,$user_name,0,$user_id,$action,$my_id);
            return true;
        }else{
            $this->write_message_log($user_phone,0,$user_name,0,$user_id,$action,$my_id);
            return false;
        }
    }

    /**
     * 写入记录短信发送记录
     * @param $phone
     * @param $state
     * @param $name
     * @param $role
     * @param $user_id
     * @param $message_tem
     * @param $templates_id
     */
    private function  write_message_log($phone, $state, $name, $role, $user_id, $message_tem, $templates_id){
        $message_log['con_phone'] = $phone;
        $message_log['state'] = $state;
        $message_log['consignee'] = $name;

        $con_type = M("users")->where(array('user_id'=>$user_id))->getField('user_rank');

        if($con_type){
            $message_log['con_type'] = $con_type;
        }else{
            $message_log['con_type'] = 0;
        }

        $message_log['user_id'] = $user_id;
        $message_log['send_content'] = $message_tem;
        $message_log['templates_id'] = $templates_id;
        $message_log['send_time'] = date('Y-m-d H:i:s',time());

//        dd($message_log);
        M("message_log")->add($message_log);
    }


    private function send_message_api_netease($template_id=null,$phone=array(),$param=array()){
        //return true;
        //网易云信短信发送测试
        //$phone = array("15820245055");
        //$param = array("name",'order_sn');
        //网易云信短信发送测试
        if (!empty($template_id)||!empty($phone)||!empty($param)){
            $data_mobile = json_encode($phone);
            $data_params = json_encode($param);
            $res = $this->requst($template_id,$data_mobile,$data_params);
            $send_re = json_decode($res,true);
            if($send_re['code']==200){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
        //dump($html);
    }
    private function requst($templateid,$mobiles,$params){
        $appKey = C("AppKey");
        $appSecret = C("AppSecret");
        $nonce = rand(100000,999999);
        $curTime = time();
        $checkSum = sha1($appSecret . $nonce . $curTime);
        $opts = array (
            'http' => array(
                'method' => 'POST',
                'header' => array(
                    'Content-Type:application/x-www-form-urlencoded;charset=utf-8',
                    "AppKey:$appKey",
                    "Nonce:$nonce",
                    "CurTime:$curTime",
                    "CheckSum:$checkSum"
                ),
                'content' =>  'templateid='.$templateid.'&mobiles='.$mobiles.'&params='.$params
            ),
        );
        //return $opts;
        $context = stream_context_create($opts);
        $html = file_get_contents(C('NETEASE_API_URL'), false, $context);
        //w_log("log",$html);
        return $html;
    }
    


}
